/**
 * 应用级别事件处理
 */
import { message } from 'antd';
import ep from '@/utils/eventproxy';
import Cookies from 'js-cookie';
import storejs from 'storejs';
import { getStore } from '@/utils/otherUtil';
import { history } from 'umi';
import { requestAfter, loginAfter, clearLoginAfter } from '@/events/rxEvent';

// BasicLayout 初始化
ep.on('basicLayoutInit', async function(data) {
   
  var token = storejs('token');
  var autoLogin = storejs('autoLogin');
  var Ctoken = Cookies.get('token');

  var goLogin = () => history.replace('/user/login');

  // 没token
  if (!token) {
    goLogin();
    return;
  }

  // 不自动登录 并且Cookies 中也没有userId
  if (autoLogin == 'false' && !Ctoken) {
    storejs.remove('token');
    storejs.remove('userId');
    goLogin();
    return;
  }

  var store = getStore();
  await store.dispatch({ type: 'user/getUserinfo' });
});

// token 失效
ep.on('tokenError', function(data) {
  var token = storejs('token');
  if (!token) return;
  var store = getStore();
  store.dispatch({ type: 'user/clearLogin' });
  setTimeout(() => {
    message.error('登录授权过期,请重新登录');
  }, 1000);
});

// 修改主题之后
ep.on('themeAfter', function(data) {});

// request 之后
requestAfter.subscribe(data => {});

// request 之后 (防抖)
requestAfter.debounceTime(2000).subscribe(data => {});

// 登录之后
loginAfter.subscribe(data => {});

// 退出登录之后
clearLoginAfter.subscribe(data => {});
